const express = require("express");
const apiRouter = express.Router();
const fs = require("fs");
const writeData = require("../../../db/module/writeData");
const readData = require("../../../db/module/readData");
const delData = require("../../../db/module/delData");
const axios = require("axios");
let appid = "92387244";
let appsecret = "sCBo8sdk";

// 文件上传中间件

// 查询天气接口
apiRouter.post("/getWeatherList", async (req, res) => {
  // 获取到客户端通过查询字符串发送到服务器的数据;
  let cityList = [
    "上海",
    "北京",
    "深圳",
    "重庆",
    "广州",
    "苏州",
    "成都",
    "杭州",
    "武汉",
    "南京",
    "宁波",
    "天津",
    "青岛",
    "无锡",
    "泉州",
    "福州",
    "济南",
    "合肥",
    "长沙",
    "常州",
    "烟台",
    "温州",
    "大连",
  ];
  let weatherList = [];

  for (let i = 0; i < 4; i++) {
    let random = Math.floor(Math.random() * cityList.length);
    let city = cityList[random];

    cityList.splice(random, 1);

    let weather = await axios.get(
      `http://gfeljm.tianqiapi.com/api?unescape=1&version=v61&appid=${appid}&appsecret=${appsecret}&city=${city}`
    );
    let next_seven_days_weather = await axios.get(
      `http://gfeljm.tianqiapi.com/api?unescape=1&version=v91&appid=${appid}&appsecret=${appsecret}&city=${city}`
    );

    weatherList.push({
      ...weather.data,
      next_seven_days_weather: next_seven_days_weather.data.data,
    });
  }

  res.send({
    code: 20000,
    msg: "查询成功",
    data: weatherList,
  });
});

// 通过城市查询天气
apiRouter.post("/getQueryCityWeather", async (req, res) => {
  const query = req.body;

  let result = await axios.get(
    `http://gfeljm.tianqiapi.com/api?unescape=1&version=v91&appid=${appid}&appsecret=${appsecret}&city=${query.city}`
  );

  res.send({
    code: 20000,
    msg: "查询成功",
    data: result.data.data,
  });
});

// 查询历史天气
apiRouter.post("/getHistoryWeather", async (req, res) => {
  const query = req.body;

  if (!query.city) {
    query.city = "101120101";
  }

  let result = await axios.get(
    `http://gfeljm.tianqiapi.com/free/history?appid=${appid}&appsecret=${appsecret}&cityid=${query.city}&date=${query.date}`
  );

  res.send({
    code: 20000,
    msg: "查询成功",
    data: result.data,
  });
});

module.exports = apiRouter;
